import requests
from settings import AppKey, AppSecret


# 获取钉钉token
class Authenticate:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        url = 'https://oapi.dingtalk.com/gettoken?appkey={}&appsecret={}'.format(AppKey, AppSecret)
        response = requests.get(url)
        if response.status_code == 200:
            res = response.json()
            token = res['access_token']
            if len(args) == 0:
                return self.func(token)
            else:
                return self.func(token, args[0])
        else:
            raise Exception('Authentication failed')


class DingTalk:
    # 获取department_id与组织架构对应关系
    @staticmethod
    @Authenticate
    def get_department_list(token):
        url = 'https://oapi.dingtalk.com/department/list?access_token={}'.format(token)
        response = requests.get(url)
        if response.status_code == 200:
            res = response.json()['department']
            dpt_dict = {}
            for dpt in res:
                dpt_dict[dpt['id']] = dpt['name']
            return dpt_dict
        else:
            return {}

    # 获取父级部门的department_id
    @staticmethod
    @Authenticate
    def get_parentIds(token, Id):
        url = 'https://oapi.dingtalk.com/department/list_parent_depts_by_dept?access_token=%s&id=%s' % (
            token, Id)
        response = requests.get(url)
        if response.json()['errcode'] == 0:
            parentIds = response.json()['parentIds']
            if len(parentIds) > 1:
                return parentIds[1]
            else:
                return parentIds[0]
        else:
            return False

    # 获取部门所有员工的usrid
    @staticmethod
    @Authenticate
    def get_userid_list(token, department_id):
        url = "https://oapi.dingtalk.com/user/simplelist?access_token={}&department_id={}".format(
            token, department_id)
        response, userIdList = requests.get(url).json(), []
        if response['errcode'] == 0:
            for user in response["userlist"]:
                userIdList.append(user['userid'])
            return userIdList
        else:
            return []
